<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-22
 * Time: 15:02:24
 * Info: 权限节点控制器
 */

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\model\AuthRule as AuthRuleModel;
use think\facade\View;
use app\common\service\admin\CacheClearService;

class AuthRule extends Base
{

    /**
     * 权限列表
     * @return \support\Response|\think\response\Json|\think\response\View
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = AuthRuleModel::where(['delete_time' => 0])->order("sort asc,id asc")->select();
            $this->success('ok', $list);
        }

        return View::fetch();
    }

    /**
     * 添加权限
     * @return \support\Response|\think\response\Json|\think\response\View
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['pid'])) {
                $param['pid'] = 0;
            }
            if (empty($param['title'])) {
                $this->error(__('%s CantBeEmpty', [__('AuthRuleTitle')]));
            }
            if (empty($param['node'])) {
                $this->error(__('%s CantBeEmpty', [__('AuthRuleNode')]));
            }
            if (strpos($param['node'], "/") === 0) {
                $param['node'] = substr($param['node'], 1);
            }

            $param['icon'] = ! empty($param['icon']) ? (string)$param['icon'] : 'layui-icon-circle-dot';
            //查询是否已存在
            $findData = AuthRuleModel::where('node', $param['node'])->find();
            if ( ! empty($findData)) {
                $this->error(__('PermissionExists'));
            }

            $lang_key          = $this->getLangKey($param['node']);
            $param['lang_key'] = $lang_key;

            AuthRuleModel::create($param);
            $adminId = cmf_get_admin_id();
            //清除缓存
            CacheClearService::clearAdminMenu('cacheAdminMenuId'.$adminId);
            //清除后台菜单缓存
            CacheClearService::clearMenu($adminId);

            //写入语言包：
            $langList    = config('lang.allow_lang_list');
            $currentLang = config('lang.default_lang'); // 获取当前语言
            foreach ($langList as $l) {
                $langPath    = __DIR__."/../lang/".$l."/admin_menu.php";
                $insertTitle = [];

                // 根据语言类型设置键值对
                if ( ! empty($param['title'])) {
                    // 只有当前语言环境才使用提交的标题，其他语言保留空值或已有翻译
                    if ($l === $currentLang) {
                        $insertTitle = [$lang_key => $param['title']];
                    }
                }

                // 如果有数据，写入语言文件
                if ( ! empty($insertTitle)) {
                    $this->writeLangFile($langPath, $insertTitle);
                }
            }

            $this->success(__('OperationSuccess'));

        }
        $id      = (int)input('get.id');
        $pidList = AuthRuleModel::getPidMenuList();

        View::assign('id', $id);
        View::assign('pidList', $pidList);

        return View::fetch();
    }

    /**
     * 编辑权限
     * @return \support\Response|\think\response\Json|\think\response\View
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['pid'])) {
                $param['pid'] = 0;
            }
            if (empty($param['id'])) {
                $this->error(__('ParamError'));
            }
            if (empty($param['title'])) {
                $this->error(__('%s CantBeEmpty', [__('AuthRuleTitle')]));
            }
            if (empty($param['node'])) {
                $this->error(__('%s CantBeEmpty', [__('AuthRuleNode')]));
            }
            if (strpos($param['node'], "/") === 0) {
                $param['node'] = substr($param['node'], 1);
            }

            $param['icon'] = ! empty($param['icon']) ? (string)$param['icon'] : 'layui-icon-circle-dot';
            //查询是否已存在
            $findData = AuthRuleModel::where('node', $param['node'])->where('id', '<>', $param['id'])->find();
            if ( ! empty($findData)) {
                $this->error(__('PermissionExists'));
            }

            $lang_key          = $this->getLangKey($param['node']);
            $param['lang_key'] = $lang_key;

            AuthRuleModel::update($param, ['id' => $param['id']]);
            $adminId = cmf_get_admin_id();
            //清除缓存
            CacheClearService::clearAdminMenu('cacheAdminMenuId'.$adminId);
            //清除后台菜单缓存
            CacheClearService::clearMenu($adminId);

            //写入语言包：
            $langList    = config('lang.allow_lang_list');
            $currentLang = config('lang.default_lang'); // 获取当前语言
            foreach ($langList as $l) {
                $langPath    = __DIR__."/../lang/".$l."/admin_menu.php";
                $insertTitle = [];

                // 根据语言类型设置键值对
                if ( ! empty($param['title'])) {
                    // 只有当前语言环境才使用提交的标题，其他语言保留空值或已有翻译
                    if ($l === $currentLang) {
                        $insertTitle = [$lang_key => $param['title']];
                    }
                }

                // 如果有数据，写入语言文件
                if ( ! empty($insertTitle)) {
                    $this->writeLangFile($langPath, $insertTitle);
                }
            }

            $this->success(__('OperationSuccess'));
        }
        $id   = (int)input('get.id');
        $data = AuthRuleModel::where(['id' => $id])->find();
        if (empty($data)) {
            $this->error(__('FailedToGetData'));
        }
        $pidList = AuthRuleModel::getPidMenuList();

        View::assign('id', $id);
        View::assign('data', $data);
        View::assign('pidList', $pidList);

        return View::fetch();
    }

    /**
     * 删除权限
     * @return \support\Response|\think\response\Json|\think\response\View
     */
    public function delete()
    {
        $id = (int)input('get.id');
        if (empty($id)) {
            $this->error(__('ParamError'));
        }
        //查询数据
        $findData = AuthRuleModel::where(['id' => $id])->find();
        if (empty($findData)) {
            $this->error(__('FailedToGetData'));
        }

        //查询子级是否存在
        $findPidData = AuthRuleModel::where(['pid' => $id])->count();
        if ($findPidData > 0) {
            $this->error(__('DeleteSubFirst'));
        }
        AuthRuleModel::destroy(['id' => $id]);
        $adminId = cmf_get_admin_id();
        //清除缓存
        CacheClearService::clearAdminMenu('cacheAdminMenuId'.$adminId);
        //清除后台菜单缓存
        CacheClearService::clearMenu($adminId);

        $lang_key = $this->getLangKey($findData['node']);
        // 删除语言包：
        $langList = config('lang.allow_lang_list');
        foreach ($langList as $l) {
            $langPath    = __DIR__."/../lang/".$l."/admin_menu.php";
            $insertTitle = [];
            $this->writeLangFile($langPath, $insertTitle, [$lang_key]);
        }

        $this->success(__('OperationSuccess'));
    }

    /**
     * 列表页的操作
     * @return void
     */
    public function modify()
    {
        if ($this->request->isAjax()) {
            $id = (int)input('id');
            if (empty($id)) {
                $this->error(__('ParamError'));
            }
            $field = input('field');
            $val   = input('val');
            AuthRuleModel::update([$field => $val], ['id' => $id]);
            //清除缓存
            $adminId = cmf_get_admin_id();
            CacheClearService::clearAdminMenu('cacheAdminMenuId'.$adminId);
            //清除后台菜单缓存
            CacheClearService::clearMenu($adminId);

            $this->success(__('OperationSuccess'));
        }

    }

    /**
     * 写入语言文件
     *
     * @param string $filePath 文件路径
     * @param array  $data     语言数据
     */
    protected function writeLangFile($filePath, $data = [], $deleteKeys = [])
    {
        // 如果文件不存在，创建文件
        if ( ! file_exists($filePath)) {
            file_put_contents($filePath, "<?php\n\nreturn [];");
        }

        // 读取现有数据
        $existingData = include $filePath;
        $existingData = $existingData['auth_menu'] ?? [];

        // 删除指定键
        foreach ($deleteKeys as $key) {
            if (isset($existingData[$key])) {
                unset($existingData[$key]);
            }
        }

        // 添加或更新键值对（改进逻辑：仅在值不存在时添加，避免覆盖已有翻译）
        foreach ($data as $key => $value) {
            // 只有当键不存在时才添加，防止覆盖已有的翻译
            if ( ! array_key_exists($key, $existingData)) {
                $existingData[$key] = $value;
            }
        }

        $existingData = ['auth_menu' => $existingData];

        $content = "<?php\n\nreturn ".var_export($existingData, true).";";
        file_put_contents($filePath, $content);
    }

    private function getLangKey($node)
    {
        $node_arr = explode('/', $node);
        if (count($node_arr) >= 3) {
            $lang_key = strtoupper($node_arr[0].'_'.$node_arr[1].'_'.$node_arr[2]);
        } elseif (count($node_arr) == 2) {
            $lang_key = strtoupper('admin'.'_'.$node_arr[0].'_'.$node_arr[1]);
        } else {
            $lang_key = strtoupper('admin'.'_'.$node_arr[0]);
        }

        return $lang_key;
    }

}
